package com.dxyxx.framework;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.type.JavaType;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

import com.android.customized.BadgeView;
import com.android.customized.FixedHeaderScrollView;
import com.android.customized.HorizontalListView;
import com.android.customized.HorizontalListViewAdapter;
import com.android.customized.MyAdGallery;
import com.android.customized.MyAdGallery.MyOnItemClickListener;
import com.dxyxx.R;
import com.dxyxx.db.BadgeContentObserver;
import com.dxyxx.db.DataChangeProvider;
import com.dxyxx.db.DataQueryUtils;
import com.dxyxx.db.ShoppingCarContentObserver;
import com.dxyxx.db.ShoppingCarDBHelper;
import com.dxyxx.framework.ShoppingCarFragment.MyInnerHandler;
import com.dxyxx.pojo.Product;
import com.dynamic.WriteActivity;
import com.http.HttpUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

/**
 * 这里有一个bug。。 反注册
 * 
 * @author Administrator
 * 
 */
public class BuyProductActivity extends BaseActivity {
	private final static String ID = "id";
	private final static String DESCRIPTION = "description";
	private final static String SPECIFICATION = "specification";
	private final static String PRICE = "price";
	private final static String THUMB = "thumb";
	private final static String IMAGEIDS = "imageIds";
	HorizontalListView hListView;
	private String categoryId;
	HorizontalListViewAdapter hListViewAdapter;
	ImageView previewImg;
	View olderSelectView = null;
	DisplayImageOptions options;
	private TextView name;
	private TextView specification;
	private TextView price;

	String[] imageUrls;
	private MyAdGallery gallery; // 广告控件
	LinearLayout ovalLayout; // 圆点容器
	/** 图片id的数组,本地测试用 */
	private int[] imageId = new int[] { R.drawable.img01, R.drawable.img02, R.drawable.img03, R.drawable.img04 };
	/** 图片网络路径数组 */
	private String[] mris = {};
	private ShoppingCarDBHelper dbHelper;
	private SQLiteDatabase sqliteDatabase;
	private Bundle bundle;

	/**
	 * 
	 * @param shareUrl
	 * @param text
	 */
	private void showShare(String text, String titleUrl, String imageUrl, String url) {
		//ShareSDK.initSDK(BuyProductActivity.this);
		OnekeyShare oks = new OnekeyShare();
		//关闭sso授权
		oks.disableSSOWhenAuthorize();

		// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
		//oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
		// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
		oks.setTitle(getString(R.string.share));
		// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
		//oks.setTitleUrl("http://dxyxx.com");
		oks.setTitleUrl(titleUrl);
		// text是分享文本，所有平台都需要这个字段
		//oks.setText("超级大芒果，快来抢啊。http://pay.dxyxx.com:8080/chinesejie/html/wcpay/wcPay.html?id=1");
		oks.setText(text);
		// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
		// oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片 没有这个图片，微信分享会失败。
		//oks.setImageUrl("http://pay.dxyxx.com:4869/aebc22ab8730baf17ae7a9177e5cdd38?p=0");
		oks.setImageUrl(baseImageURL + imageUrl + "?p=0");
		// url仅在微信（包括好友和朋友圈）中使用
		//oks.setUrl("http://pay.dxyxx.com:8080/chinesejie/html/wcpay/wcPay.html?id=1");
		oks.setUrl(url);
		// comment是我对这条分享的评论，仅在人人网和QQ空间使用
		oks.setComment("这家店还不错！");
		// site是分享此内容的网站名称，仅在QQ空间使用
		oks.setSite(getString(R.string.app_name));
		// siteUrl是分享此内容的网站地址，仅在QQ空间使用
		oks.setSiteUrl("http://rs88881234.com");

		// 启动分享GUI
		oks.show(BuyProductActivity.this);
	}

	private String[] htitles;
	private String[] himages;
	private String[] hspecifications;
	private String[] hprices;
	private String[] hids;
	private String[] hthumbs;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_buyproduct);
		bundle = this.getIntent().getExtras();
		categoryId = bundle.getString("categoryId");
		initViews();
		name.setText(bundle.getString(DESCRIPTION));
		specification.setText(bundle.getString(SPECIFICATION));
		price.setText(bundle.getString(PRICE));
		// 填充 分享字段 
		String url_temp = "https://rs88881234.com/chinesejie/html/wx/index.html#/wcPay?id=" + bundle.getString(ID);
		text = "超级 " + bundle.getString(DESCRIPTION) + "，快来抢啊。 " + url_temp;//分享文本
		titleUrl = url_temp;//分享的题目
		imageUrl = bundle.getString(THUMB);//分享的图片
		url = url_temp;//分享的网址
		// 设置轮播广告长度宽度
		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		int width = metric.widthPixels; // 屏幕高度（像素）
		FrameLayout.LayoutParams fl = (android.widget.FrameLayout.LayoutParams) gallery.getLayoutParams();
		fl.height = (int) width;
		fl.width = (int) width;
		gallery.setLayoutParams(fl);

		// 接收name值
		String imageIds = bundle.getString(IMAGEIDS);
		String[] ivs = imageIds.split(";");
		mris = new String[ivs.length];
		int i = 0;
		for (String temp : ivs) {
			mris[i] = baseImageURL + temp + "?p=0";
			i++;
		}
		// 第二和第三参数 2选1 ,参数2为 图片网络路径数组 ,参数3为图片id的数组,本地测试用 ,2个参数都有优先采用 参数2
		gallery.start(this, mris, imageId, 3000, ovalLayout, R.drawable.dot_focused, R.drawable.dot_normal);
		gallery.setMyOnItemClickListener(new MyOnItemClickListener() {
			public void onItemClick(int curIndex) {
				Toast.makeText(BuyProductActivity.this, "点击的图片下标为:" + curIndex, Toast.LENGTH_SHORT).show();
				// System.out.println(curIndex);
			}
		});
		((FixedHeaderScrollView) (findViewById(R.id.fixedScrollView))).setHeaderView(findViewById(R.id.headerView));

		// / 水平滑动
		hListView = (HorizontalListView) findViewById(R.id.horizon_listview);
		previewImg = (ImageView) findViewById(R.id.image_preview);
		//		hListViewAdapter = new HorizontalListViewAdapter(this, titles, ids);
		//		hListView.setAdapter(hListViewAdapter);

		//		启动网络得到同类商品
		String url = "product/list?current=1&count=5&order=hot&categoryId=" + categoryId;
		HttpUtil.get(url, new AsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {

				try {
					JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(List.class, Product.class);
					List<Product> items = getObjectMapper().readValue(arg2, javaType);
					htitles = new String[items.size()];
					himages = new String[items.size()];
					hspecifications = new String[items.size()];
					hprices = new String[items.size()];
					hids = new String[items.size()];
					hthumbs = new String[items.size()];
					String[] hthumbsWithHttp = new String[items.size()];

					int i = 0;
					for (Product p : items) {

						htitles[i] = p.getDescription();
						himages[i] = p.getImageIds();
						hspecifications[i] = p.getSpecification();
						hprices[i] = p.getPrice() + "";
						hids[i] = p.getId() + "";
						hthumbs[i] = p.getThumbId() + "";
						hthumbsWithHttp[i] = baseImageURL + p.getThumbId() + "?p=0";
						i++;
					}
					hListViewAdapter = new HorizontalListViewAdapter(BuyProductActivity.this, htitles, hthumbsWithHttp, hspecifications, hprices, imageLoader);
					hListView.setAdapter(hListViewAdapter);
					hListView.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {

							Intent intent = new Intent(BuyProductActivity.this, BuyProductActivity.class);

							// 用Bundle携带数据
							Bundle bundle = new Bundle();
							//传三个值 过去。
							bundle.putString(ID, hids[position]);
							bundle.putString("categoryId", categoryId);

							bundle.putString(DESCRIPTION, htitles[position]);
							bundle.putString(THUMB, hthumbs[position]);
							bundle.putString(IMAGEIDS, himages[position]);
							bundle.putString(PRICE, hprices[position]);
							bundle.putString(SPECIFICATION, hspecifications[position]);
							intent.putExtras(bundle);

							startActivityForResult(intent, RequestCode.Product);
							finish();// finish输掉自己
						}

					});

				} catch (JsonParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JsonMappingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {

			}
		});

		View target = findViewById(R.id.cart);
		target.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent();
				// 把返回数据存入Intent
				intent.putExtra("result", "cart");
				// 设置返回数据
				BuyProductActivity.this.setResult(ResultCode.Product, intent);

				BuyProductActivity.this.finish();
			}
		});
		badge = new BadgeView(this, target);
		badge.setText(DataQueryUtils.getProductsCount(getApplicationContext(), DataChangeProvider.CONTENT_URI) + "");
		badge.show();
		findViewById(R.id.paynow).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// 数据库操作
				ContentValues contentValues = new ContentValues();
				contentValues.put("pid", Integer.parseInt(bundle.getString(ID)));
				contentValues.put(DESCRIPTION, bundle.getString(DESCRIPTION));
				contentValues.put(SPECIFICATION, bundle.getString(SPECIFICATION));
				contentValues.put(PRICE, bundle.getString(PRICE));
				contentValues.put(THUMB, bundle.getString(THUMB));
				contentValues.put("amount", Integer.parseInt(amount.getText().toString()));
				getContentResolver().insert(com.dxyxx.db.DataChangeProvider.CONTENT_URI, contentValues);
			}
		});

		findViewById(R.id.detail).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				Intent intent = new Intent(BuyProductActivity.this, ProductDetailActivity.class);
				intent.putExtra("productId", bundle.getString(ID));
				startActivity(intent);

			}
		});

		findViewById(R.id.comment).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				Intent intent = new Intent(BuyProductActivity.this, ProductCommentActivity.class);
				intent.putExtra("productId", bundle.getString(ID));
				startActivity(intent);

			}
		});
	}

	private Button addButton;
	private Button minusButton;
	private TextView amount;
	private BadgeView badge;
	// 分享四个 字段。。
	private String text;//分享文本
	String titleUrl;//分享的题目
	String imageUrl;//分享的图片
	String url;//分享的网址

	private void initViews() {
		ImageView backImageView = (ImageView) findViewById(R.id.backImageView);
		backImageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		ImageView say = (ImageView) findViewById(R.id.say);
		say.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(BuyProductActivity.this, WriteActivity.class);
				intent.putExtra("productId", bundle.getString(ID));
				startActivity(intent);
			}
		});

		ImageView share = (ImageView) findViewById(R.id.share);
		share.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				showShare(text, titleUrl, imageUrl,  url);
			}
		});

		name = (TextView) findViewById(R.id.name);
		specification = (TextView) findViewById(R.id.specification);
		price = (TextView) findViewById(R.id.price);
		gallery = (MyAdGallery) findViewById(R.id.adgallery); // 获取Gallery组件;
		ovalLayout = (LinearLayout) findViewById(R.id.ovalLayout);// 获取圆点容器

		// 增加减少 的按钮
		addButton = (Button) findViewById(R.id.add);
		minusButton = (Button) findViewById(R.id.minus);
		amount = (TextView) findViewById(R.id.amount);

		addButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				int temp = Integer.parseInt((amount.getText().toString())) + 1;
				amount.setText(temp + "");
			}
		});

		minusButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				int temp = Integer.parseInt((amount.getText().toString())) - 1;
				if (temp > 0) {
					amount.setText(temp + "");
				}
			}
		});

	}

	//** 避免  handler 内存泄露。 见http://stackoverflow.com/questions/11278875/handlers-and-memory-leaks-in-android
	static class MyInnerHandler extends Handler {
		WeakReference<BuyProductActivity> mActivity;

		MyInnerHandler(BuyProductActivity activity) {
			mActivity = new WeakReference<BuyProductActivity>(activity);
		}

		@Override
		public void handleMessage(Message message) {
			BuyProductActivity theActivity = mActivity.get();
			if (theActivity != null) {

				int count = DataQueryUtils.getProductsCount(theActivity.getApplicationContext(), DataChangeProvider.CONTENT_URI);
				if (count != 0) {
					// 更新 个数
					theActivity.badge.setText(count + "");
					theActivity.badge.show();
				} else {
					theActivity.badge.hide();
				}
			}
		}
	}

	private MyInnerHandler myHandler = new MyInnerHandler(this);
	private BadgeContentObserver observer;

	// //注册数据库cart监听
	@Override
	public void onResume() {

		super.onResume();
		if (observer == null) {
			observer = new BadgeContentObserver(myHandler);
		}
		//设置监听
		getContentResolver().registerContentObserver(DataChangeProvider.CONTENT_URI, true, observer);
	}

	//删除监听..此处不能删除监听
	@Override
	public void onStop() {
		super.onStop();
		if (observer != null) {
			getContentResolver().unregisterContentObserver(observer);
		}
	}
}
